<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2012 HongPing All rights reserved.
// +----------------------------------------------------------------------
// | ActionName:销售退货单
// +----------------------------------------------------------------------
// | Author: HongPing <hongping626@qq.com>
// +----------------------------------------------------------------------
class SalebackAction extends CommonAction {
	function _filter(&$map){
        //$map['id'] = array('egt',2);
		//$map['wahname|egname|wahcode|wahaddr'] = array('like',"%".$_POST['selectname']."%");
        
	}
   //页面加载前生产单据编号
    function _before_index(){
        $newCode = $this->getSerialNum('XT','Ordermain');
        
        $bankM = M('Bankaccount');
        $mapM['status'] = 1;
        $listBank = $bankM->where($mapM)->select();
        
        $this->assign ( 'listBank', $listBank );
        $this->assign ( 'newCode', $newCode );
        $this->assign ( 'dtime', date('Y-m-d') );
    }
    
    function addOrders(){
        //$this->error($_POST['goStock']);exit;
        if($_POST['ordernumber']){$mainData['ordernumber'] = $_POST['ordernumber'];}else{$this->error('单据编号不能为空。');exit;}//單據編號
        $mainData['invoicenumber'] = $_POST['invoices'];//发票号码
        if($_POST['sendName_id']){$mainData['contactid'] = $_POST['sendName_id'];}else{$this->error('退货单位不能为空。');exit;}//退货单位
        if($_POST['ordertime']){$mainData['ordertime'] = strtotime($_POST['ordertime']);}else{$this->error('单据日期不能为空。');exit;}//單據日期        
        if($_POST['orderUser_id']){$mainData['orderuser'] = $_POST['orderUser_id'];}else{$this->error('经办人不能为空。');exit;}//经办人
        if($_POST['warehouse_id']){$mainData['warehouse'] = $_POST['warehouse_id'];}else{$this->error('接收仓库不能为空。');exit;}//接收仓库        
        $mainData['remarks'] = $_POST['remarks'];//摘要
        if($_POST['total_nums']){$mainData['ordernums'] = $_POST['total_nums'];}else{$this->error('商品数量为0。');exit;}//单据數量
        $mainData['oddamount'] = $_POST['odd_amount'];//折扣金额
        $mainData['orderamount'] = $_POST['total_amount'];//应付金额
        $mainData['payamount'] = $_POST['trade_amount'];//实付金额
        $mainData['createuser'] = $_SESSION[C('USER_AUTH_KEY')];//制单人
        $mainData['bankid'] = $_POST['bankid'];//付款账户
        $mainData['ordertype'] = 4;//设置为销售退货单
        $mainData['status'] = 0;//状态未锁定
        $mainData['createtime'] = strtotime(date('Y-m-d H:i:s'));//新增时间
        $mainData['updatetime'] = strtotime(date('Y-m-d H:i:s'));//更新时间
        //$a = $items['orgNumber'];
        
                
        $aProidData = $_POST['items_proid'];
        $countRow = count($aProidData);
        if(in_array('',$aProidData)){$this->error('行数据未填写完整。');exit;}//检测数组是否有空元素
        if($countRow==0){$this->error('单据没有添加任何商品信息。');exit;}
        $aPNumbData = $_POST['items_orgNumber'];
        $aCountData = $_POST['items_orgCount'];
        $aPriceData = $_POST['items_orgPrice'];
        $aDisctData = $_POST['items_orgDiscount'];
        $aTotalData = $_POST['items_orgTotal'];
        $aMarksData = $_POST['items_orgMark'];
                    
        //模型化各操作表                     
        $orderModel = D('Ordermain');
        $detailModel = D('Orderdetails'); 
        $stockModel = D('Stocks');
        $bankModel = D('Bankaccount');    
        //设置条件                       
        $orderMap['ordernumber'] = $_POST['ordernumber'];//单据编号对应的订单总表和详细表
        
        
        if(($orderModel->where($orderMap)->count('id'))>0){$this->error('该单据已提交过,请勿重复提交单据。');exit;}
        
        //验证库存
        //  $orderNums = $mainData['ordernums'];
        //$stockMap['prodid'] = array('in',$aProidData);//查找商品对于的库存
        //$stockMap['warehid'] = $mainData['warehouse'];//查找对应的仓库库存
        //if($_POST['goStock']==1){        
        //  $stockNums = $stockModel->where($stockMap)->sum('stocknums');
        //  if(bccomp($stockNums,$orderNums)<0){$this->error('当前库存量不足,无法结算库存量');exit;}  
        //}
        
        //验证账户余额
        $bankMap['id'] = $mainData['bankid'];
        $bankMap['status'] = 1;
        $orderAccount = $mainData['payamount'];
        if($_POST['goFunds']==1){           
           $bankAccount  = $bankModel->where($bankMap)->sum('bamount');
           if(bccomp($bankAccount,$orderAccount)<0){$this->error('当前账户余额不足,无法结算金额');exit;} 
        }
        
        
        //开始数据写入
        if($orderModel->add($mainData)){                 
                //循环本单据每笔单据信息写入数据库
                $k = 0;
                $sucsCount = 0;
                for($i=0;$i<$countRow;$i++){                    
                    unset($detailData);
                    if($aProidData[$i]!='' and $aProidData[$i]!=0){
                        $k = $k+1;
                        $detailData['ordersort']   = $k;
                        $detailData['ordernumber'] = $_POST['ordernumber'];
                        $detailData['prodid']      = $aProidData[$i];
                        $detailData['prodcode']    = $aPNumbData[$i];
                        $detailData['ordernums']   = $aCountData[$i];
                        $detailData['orderprice']  = $aPriceData[$i];
                        $detailData['discounts']   = $aDisctData[$i];
                        $detailData['totalamount'] = $aTotalData[$i];
                        $detailData['remarks']     = $aMarksData[$i];
                        $detailData['iotype']      = 1;//1为入库2为出库                            
                    }
                    
                    if($detailModel->add($detailData)){
                        //庫存操作
                        if($_POST['goStock']==1){//如果有选择结库                                
                            $stkMap['prodid'] = $detailData['prodid'];
                            $stkMap['warehid'] = $mainData['warehouse'];
                            $stkCount = $stockModel->where($stkMap)->count('id');
                            if($stkCount>0){//库存商品已有该商品库存
                               $stockModel->where($stkMap)->setInc('stocknums',$detailData['ordernums']);//增加库存量
                               $stockModel->where($stkMap)->setField('updatetime',time());//更新库存时间
                            }else{
                               $stkData['prodid'] = $detailData['prodid'];
                               $stkData['stocknums'] = $detailData['ordernums'];
                               $stkData['warehid'] = $mainData['warehouse'];
                               $stkData['updatetime'] = time();
                               $stockModel->add($stkData);//增加商品库存
                            }
                            
                        }
                        //计数器
                        $sucsCount = $sucsCount+1;
                    }
                }                    
            if($sucsCount == $countRow){                    
                //資金操作
                if($_POST['goFunds']==1){//有选择结款
                    //$upBank = array('stocknums'=>'stocknums - '.$orderAccount,'updatetime'=>time());
                    $bankModel->where($bankMap)->setDec('bamount',$orderAccount);//setField($upBank);//减少账户余额                    
                    $orderModel->where($orderMap)->setField('paystatus',1);//结款状态                    
                }
                if($_POST['goStock']==1){
                        $orderModel->where($orderMap)->setField('stkstatus',1);//结库状态
                }
               $this->assign ( "jumpUrl", $this->getReturnUrl());
               $this->success('单据[ '.$_POST['ordernumber'].' ]提交成功。'); 
            }else{
               $orderModel->where($orderMap)->delete();
               $detailModel->where($orderMap)->delete();
               $this->error('单据[ '.$sucsCount.$countRow.$_POST['ordernumber'].' ]提交失敗,请检查数据是否正确。');                   
            }                
        }else{
            $this->error('单据保存失败。');
        }
               
    }

    
 
}
?>